<template>
    <a-button type="primary" @click="startRecording">开始录音</a-button>
    <a-button type="primary" @click="stopRecording">停止录音</a-button>
    <a-button type="primary" @click="downloadAudio">下载音频</a-button>
    <a-button type="primary" @click="uploadAudio">上传音频</a-button>
</template>

<script setup>
import { ref } from 'vue'
import Recorder from 'recorder-core'
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
import 'recorder-core/src/engine/wav'
import { post } from '@/utils/http/Axios'
let recorder = ref(null)
let audioBlob = ref(null)

const startRecording = () => {
    recorder.value = new Recorder({ type: 'wav' })
    recorder.value.open(
        () => {
            // 在 open 方法成功回调之后开始录音
            recorder.value.start()
        },
        error => {
            // 处理打开录音设备失败的情况
            console.error(error)
        }
    )
}

const stopRecording = () => {
    recorder.value.stop(blob => {
        audioBlob.value = blob
    })
}

const downloadAudio = () => {
    const url = URL.createObjectURL(audioBlob.value)
    const a = document.createElement('a')
    a.href = url
    a.download = 'audio.wav'
    a.click()
}

const uploadAudio = async () => {
    const formData = new FormData()
    formData.append('file', audioBlob.value, 'audio.wav')
    const response = await post('/getWord', formData)
    const data = await response.json()
    console.log(data)
}
</script>
